<template>
  <span :class="[btnProps && btnProps.block ? 'block' : 'inline-block']" @click="click">
    <a-button v-if="_hasPermission && !disabledMes" class="permission-btn" v-bind="btnProps" @focus="focus">
      <slot name="icon" />
      <slot />
    </a-button>
    <a-tooltip v-else :title="disabledMes || t('common.noAuthShort')" :destroy-tooltip-on-hide="true">
      <a-button class="permission-btn" v-bind="btnProps" :disabled="true"> <slot name="icon" /><slot /> </a-button>
    </a-tooltip>
  </span>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import { usePermission } from "/@/hooks/usePermission";
import type { ButtonProps } from "ant-design-vue";
import { PermissionCode } from "/@/api/permissionCode";
import { ref } from "vue";
import { OperPermissionType } from "/@/api/aiot/role/models";

const props = withDefaults(
  defineProps<{
    btnProps?: ButtonProps;
    //接口权限编码
    permissionCode?: PermissionCode;
    //操作类型
    operType?: OperPermissionType;
    //是否有权限
    hasPermission?: boolean;
    routeName?: string;
    disabledMes?: string | null;
  }>(),
  {
    hasPermission: void 0,
  }
);
const emits = defineEmits(["click"]);
const { t } = useI18n();
let _hasPermission = ref(false);
const routeName = props.routeName as string;
if (props.hasPermission === void 0) {
  if (props.permissionCode) {
    //只指定permissionCode  根据按钮权限数据判断权限
    const { judgePermissionByCode } = usePermission({ routeName });
    _hasPermission.value = judgePermissionByCode(props.permissionCode);
  } else if (props.operType) {
    //指定操作类型，根据类型判断权限
    const { judgePermissionByOperType } = usePermission({ routeName });
    _hasPermission.value = judgePermissionByOperType(props.operType);
  } else {
    //hasPermission operType permissionCode都没指定 默认有权限
    _hasPermission.value = true;
  }
} else {
  //指定hasPermission 直接设置
  _hasPermission.value = props.hasPermission;
}
function click(e) {
  if (_hasPermission.value && !props.disabledMes) {
    emits("click", e);
  }
}
function focus(e: FocusEvent) {
  if (e.relatedTarget) {
    //解决当窗口失去焦点 按钮获得焦点的灰色样式问题
    (e.target as HTMLElement).blur();
  }
}
</script>
<style>
.ant-btn-link.permission-btn {
  padding: 0;
  height: auto;
  border: 0;
}
</style>
